package cn.bingoogolapple.qrcode.zxingdemo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import static android.view.KeyEvent.KEYCODE_BACK;

public class HomeActivity extends AppCompatActivity {

    private Button btnShow;
    private WebView webView;
    private HomeActivity context;
    private int isFrist=1; // 2,本地，1，网络，
    private String beforeUrl="http://m.wzhj365.com?wzhj_app=and";
    private String nextUrl="http://m.wzhj365.com?wzhj_app=and";
    private final String indexUrl="http://m.wzhj365.com?wzhj_app=and";
    private static String	folder	= AppUtils.getMyCacheDir();

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        context=this;
        initView();
        copyAssetsFiles();
        initData();
        initEvent();
    }
    private void initView() {
        btnShow = (Button) findViewById(R.id.btn_show);
        webView = (WebView) findViewById(R.id.webView);
    }



    private void initData() {
        webView.setWebChromeClient(new WebChromeClient());
        WebSettings webSettings= webView.getSettings();
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setJavaScriptEnabled(true);  //设置webview支持js
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
        webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能
        //设置本地调用对象及其接口Q
        webView.addJavascriptInterface(new JsInteraction(), "honglei");
//        webView.loadUrl("http333://192.168.1.123:8868/slider/index.html");//方式1. 加载一个网页：
        syncCookie(this,indexUrl);
        webView.loadUrl(indexUrl);
        //方式2：加载apk包中的html页面
       // webView.loadUrl("file:///android_asset/test.html"); //此处替换为 url网址即可 （调用android原生方法见网页）
        //方式3：加载手机本地的html页面
        //webView.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!NetWorkUtils.isConnected(context)){
                    if (!url.contains("android_asset"))
                        webView.loadUrl("file:///android_asset/E404.html");
                }else {
                    if (!nextUrl.equals(url)&!url.contains("android_asset"))
                    {
                        beforeUrl=nextUrl;
                        nextUrl=url;
                    }
                    if (url.contains("android_asset"))
                        url=nextUrl;
                    if (url.contains("android_asset"))
                        url=beforeUrl;
                    if (url.contains("android_asset"))
                        url=indexUrl;
                    isFrist=1;
                }
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                if (!NetWorkUtils.isConnected(context)){
                    if (!url.contains("android_asset")){
                        webView.loadUrl("file:///android_asset/E404.html");
                    }
                }else {
                    if (!nextUrl.equals(url)&!url.contains("android_asset"))
                    {
                        beforeUrl=nextUrl;
                        nextUrl=url;
                    }
//                    if (url.contains("android_asset"))
//                        url=nextUrl;
//                    if (url.contains("android_asset"))
//                        url=beforeUrl;
//                    if (url.contains("android_asset"))
//                      url=indexUrl;
                }
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webView.loadUrl("file:///android_asset/E404.html");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        });


        //设置WebChromeClient类
        webView.setWebChromeClient(new WebChromeClient() {
            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
            }
            //获取加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
            }
        });
    }

    private void initEvent() {
        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg="android 原生参数";
               // webView.loadUrl("javascript:sayHello()"); //本地调用js方法
                webView.loadUrl("javascript:showInfoFromJava('" + msg + "')");//调用js中的函数：showInfoFromJava(msg)
            }
        });
    }

    public class JsInteraction {
        @JavascriptInterface
        public void startScan(String msg) {   //提供给js调用的方法
           // Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            startActivityForResult(new Intent(HomeActivity.this,TestScanActivity.class),0x1);
        }

        @JavascriptInterface
        public void update() {   //提供给js调用的方法
            //Toast.makeText(getApplicationContext(), "weweww", Toast.LENGTH_LONG).show();
            webView.loadUrl(nextUrl);//调用js中的函数：showInfoFromJava(msg)
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==0x2)
        {
            if (data==null)
            return;
           // Toast.makeText(this, data.getStringExtra("result"), Toast.LENGTH_SHORT).show();
            webView.loadUrl("javascript:showInfoFromJava('" + data.getStringExtra("result")+ "')");
        }
    }

    // 设置cookie
    public static void syncCookie(Context context,String url) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除
        cookieManager.setCookie(url, "IMIE=a"+Device.getDeviceId(context));
        cookieManager.setCookie(url, "wzhj_app=and");//cookies是在HttpClient中获得的cookie
        CookieSyncManager.getInstance().sync();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /***
     * 复制assets文件到sd卡
     */
    private void copyAssetsFiles() {
        // 删除原文件，再创建文件夹
        FileUtils.delAllFile(folder);
        AppUtils.getMyCacheDir("font");

        try {
            String[] fileNames = getAssets().list("font");

            for (String fileName : fileNames) {
                copyFile("font/" + fileName, folder + "font/" + fileName);
            }

            fileNames = getAssets().list("html");
            for (String fileName : fileNames) {
                copyFile("html/" + fileName, folder + fileName);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    private void loadHtmlFromAssets() {

        String html = FileUtils.readAssest(this, "html/content.html");

        html = html.replace("@fontName0", "Impact");
        html = html.replace("@fontName1", "STANK");
        html = html.replace("@fontPath0", "../font/Impact.ttf");// assets相对路径
        html = html.replace("@fontPath1", "file://" + folder + "font/STANK.ttf");// sd卡里的ttf文件绝对路径
        html = html.replace("@image_assets", "image0.png");
        html = html.replace("@image_res", "file:///android_res/drawable/image0.png");
        html = html.replace("@image_file", "file://" + folder + "image0.png");
        String baseurl = "file:///android_asset/html/";

        webView.loadDataWithBaseURL(baseurl, html, "text/html", "UTF-8", null);
    }

    private void loadHtmlFromStorage() {
        String path = folder + "content.html";
        if (new File(path).exists()) {
            String html = FileUtils.readString(path);
            html = html.replace("@fontName0", "Impact");
            html = html.replace("@fontName1", "STANK");
            html = html.replace("@fontPath0", "file:///android_asset/font/Impact.ttf");// assets绝对路径
            html = html.replace("@fontPath1", "./font/STANK.ttf");// sd卡相对路径 ("font/STANK.ttf"也可以)
            html = html.replace("@image_assets", "file:///android_asset/html/image0.png");
            html = html.replace("@image_res", "file:///android_res/drawable/image0.png");
            html = html.replace("@image_file", "image0.png");
            String baseurl = "file://" + path;
            webView.loadDataWithBaseURL(baseurl, html, "text/html", "UTF-8", null);
        }
    }

    private void copyFile(String filename, String targetPath) {
        try {
            InputStream input = getAssets().open(filename);
            BufferedInputStream bin = new BufferedInputStream(input);

            FileOutputStream fout = new FileOutputStream(new File(targetPath));

            int hasRead;
            byte[] buffer = new byte[1024];

            while ((hasRead = bin.read(buffer)) > -1) {
                fout.write(buffer, 0, hasRead);
            }

            fout.flush();
            fout.close();

            input.close();
            bin.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
